package com.fengmi.sso.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fengmi.entity.exception.JWTParseException;
import com.fengmi.entity.sso.SysUser;
import com.fengmi.entity.vo.ResultVO;
import com.fengmi.jwt.JwtUtils;
import com.fengmi.jwt.RsaUtils;
import com.fengmi.sso.mapper.SysUserMapper;
import com.fengmi.sso.service.ISysUserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.io.FileNotFoundException;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author 小马
 * @since 2021-10-20
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Override
    public ResultVO login(SysUser user) {

        if(StringUtils.isEmpty(user))
            return new ResultVO(false,"用户名或密码没有填写");

        //获取用户信息
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",user.getAccount());
        queryWrapper.eq("user_type","6");
        SysUser sysUserFromDB = this.baseMapper.selectOne(queryWrapper);
        if(sysUserFromDB ==null )
            return new ResultVO(false,"用户名或者密码错误");

        //验证密码
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(user.getPassword(),sysUserFromDB.getPassword())){
            return new ResultVO(false,"用户名或者密码错误");
        }

        //办法令牌
        try {
            //加载私钥
            String path = ResourceUtils.getFile("classpath:rsa_pri").getPath();
            PrivateKey privateKey = RsaUtils.getPrivateKey(path);
            sysUserFromDB.setPassword("");
            String token = JwtUtils.generateTokenExpireInMinutes(sysUserFromDB, privateKey, 40);
            return new ResultVO(true,"success",token);

        } catch (Exception e) {
            e.printStackTrace();
            return new ResultVO(false,"用户名或者密码错误");
        }

    }

    @Override
    public ResultVO login(String phone, String code) {
        return null;
    }

    @Override
    public ResultVO verifyToken(String token) {
        try {
            PublicKey publicKey = null;
            try {
                publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa_pub").getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
            Object userInfo = JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);

            return new ResultVO(true,"合法令牌");

        } catch (JWTParseException e) {
            e.printStackTrace();
            return new ResultVO(false,"无效令牌");
        }

    }
}
